<template>
	<div>
		<div class="container_box">
			<div class="container_title">医院管理</div>
			<div class="container_content">
				<el-table :data="tableData" style="width: 100%">
					<el-table-column prop="name" label="医院名称" width="180" align="center" />
					<el-table-column prop="type" label="医院类型" width="180" align="center" />
					<el-table-column prop="tel" label="联系电话" width="180" align="center" />
					<el-table-column prop="address" label="医院地址" width="180" align="center" />
					<el-table-column label="医院图片" width="180" align="center">
						<template #default="scope">
							<el-image
								:src="imageUrlPrefix + scope.row.img"
								style="width: 100px; height: 60px"
								fit="cover"
								preview-teleported
								:preview-src-list="[imageUrlPrefix + scope.row.img]"
							/>
						</template>
					</el-table-column>
					<el-table-column prop="create_time" label="创建时间" width="180" align="center" />
					<el-table-column label="操作" width="180" align="center">
						<template #default="scope">
							<el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>

		<!-- 医院编辑弹窗 -->
		<el-dialog title="编辑医院信息" v-model="editDialogVisible" width="800px" @close="handleDialogClose" @opened="onDialogOpened">
			<el-form :model="hospitalForm" :rules="hospitalRules" ref="hospitalFormRef" label-width="100px">
				<el-form-item label="医院名称" prop="name">
					<el-input v-model="hospitalForm.name" placeholder="请输入医院名称"></el-input>
				</el-form-item>

				<el-form-item label="联系电话" prop="tel">
					<el-input v-model="hospitalForm.tel" placeholder="请输入联系电话"></el-input>
				</el-form-item>

				<el-form-item label="医院类型" prop="type">
					<el-input v-model="hospitalForm.type" placeholder="请输入医院类型"></el-input>
				</el-form-item>

				<el-form-item label="医院地址" prop="address">
					<el-input v-model="hospitalForm.address" placeholder="请输入医院地址"></el-input>
				</el-form-item>

				<!-- 经纬度输入框设置为禁用 -->
				<el-form-item label="经度" prop="longitude" style="width: 90%">
					<el-input v-model.trim="hospitalForm.longitude" placeholder="通过地图选择" style="width: 90%" :disabled="true" />
				</el-form-item>
				<el-form-item label="纬度" prop="latitude" style="width: 90%">
					<el-input v-model.trim="hospitalForm.latitude" placeholder="通过地图选择" style="width: 90%" :disabled="true" />
				</el-form-item>
				
				<el-form-item label="地址搜索" prop="" style="width: 90%">
					<div style="width: 90%; position: relative;">
						<el-autocomplete
							id="tipinput"
							v-model.trim="searchKeyword"
							:fetch-suggestions="querySearch"
							placeholder="请输入关键字搜索地址"
							clearable
							style="position: absolute; top: 10px; left: 10px; width: 300px; z-index: 2000; background: white; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
							@select="handleAddressSelect"
							@blur="searchOnBlur"
							@keyup.enter="searchs"
						></el-autocomplete>
						<div id="container" style="width: 100%; height: 400px;"></div>
					</div>
				</el-form-item>

				
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="医院图片" prop="img">
							<el-upload
								class="avatar-uploader"
								action="/pc/Fileimg/file"
								:show-file-list="false"
								:on-success="handleImgSuccess"
								:on-error="handleImgUploadError"
								:before-upload="beforeImgUpload"
								:on-progress="handleImgProgress"
								:disabled="imgUploadLoading"
							>
								<img v-if="hospitalForm.img" :src="imageUrlPrefix + hospitalForm.img" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus v-if="!imgUploadLoading" />
									<Loading v-else />
								</el-icon>
								<div v-if="imgUploadLoading" class="image-loading">
									<el-progress type="circle" :percentage="imgUploadProgress" :width="80" />
								</div>
							</el-upload>
							<div class="el-upload__tip">点击上传医院图片，支持JPG、PNG格式，大小不超过2MB</div>
							<div v-if="imgUploadLoading" class="upload-status">上传中...</div>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="科室分布" prop="profile">
							<el-upload
								class="avatar-uploader"
								action="/pc/Fileimg/file"
								:show-file-list="false"
								:on-success="handleProfileSuccess"
								:on-error="handleProfileUploadError"
								:before-upload="beforeProfileUpload"
								:on-progress="handleProfileProgress"
								:disabled="profileUploadLoading"
							>
								<img v-if="hospitalForm.profile" :src="imageUrlPrefix + hospitalForm.profile" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus v-if="!profileUploadLoading" />
									<Loading v-else />
								</el-icon>
								<div v-if="profileUploadLoading" class="image-loading">
									<el-progress type="circle" :percentage="profileUploadProgress" :width="80" />
								</div>
							</el-upload>
							<div class="el-upload__tip">点击上传科室分布图，支持JPG、PNG格式，大小不超过2MB</div>
							<div v-if="profileUploadLoading" class="upload-status">上传中...</div>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="详情" prop="content">
					<vue-ueditor-wrap v-model="hospitalForm.content" :config="editorConfig" editor-id="editor-hospital"> </vue-ueditor-wrap>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitForm">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted,onUpdated, nextTick, onUnmounted, watch } from 'vue';
import { getHospitalInfo,hospitalEdit } from '/@/api/hospitalList/index';
import { Plus, Search, Loading } from '@element-plus/icons-vue';
import { ElMessage, ElLoading, ElProgress } from 'element-plus';

// 地图相关变量
let placeSearch = null; // 声明placeSearch变量
let lati = ref('');
let longi = ref('');
const autoComplete = ref(null);
const hasAmapKey = ref(!!import.meta.env.VITE_AMAP_KEY);
let marker = ref(null); // 这里改为let，允许重新赋值
const geocoder = ref(null);
const searchSuggestions = ref([]); // 存储搜索建议

// 引入高德地图API
import { load } from "@amap/amap-jsapi-loader";
// 用户输入的地点关键字
const searchKeyword = ref("");
let map = null; //初始化地图

// 图片上传状态相关变量
const imgUploadLoading = ref(false);
const profileUploadLoading = ref(false);
const imgUploadProgress = ref(0);
const profileUploadProgress = ref(0);

// 获取地址建议
const querySearch = (queryString: string, cb: Function) => {
	if (!autoComplete.value || !queryString || queryString.length < 2) {
		cb([]);
		return;
	}

	// 使用setTimeout确保回调正确执行
	setTimeout(() => {
		autoComplete.value.search(queryString, (status: string, result: any) => {
			if (status === 'complete' && result.tips && result.tips.length > 0) {
				// 格式化建议数据
				const suggestions = result.tips.map((tip: any) => ({
					value: tip.id || tip.name,
					name: tip.name,
					address: tip.address || tip.district || '未知地址',
					location: tip.location,
					adcode: tip.adcode,
				}));

				// 存储建议数据用于调试
				searchSuggestions.value = suggestions;

				// 调用回调函数
				nextTick(() => {
					cb(suggestions);
				});
			} else {
				console.log('未找到地址建议', status, result);
				searchSuggestions.value = [];
				cb([]);
			}
		});
	}, 0);
};

// 处理地址选择事件
const handleAddressSelect = (item: any) => {
	if (item && item.location) {
		// 设置经纬度到表单
		hospitalForm.longitude = item.location.lng.toString();
		hospitalForm.latitude = item.location.lat.toString();
		
		// 更新地图中心和标记
		if (map) {
			map.setCenter([item.location.lng, item.location.lat]);
			map.setZoom(15);
			
			// 添加标记并绑定点击事件
			addMarkerWithClickEvent([item.location.lng, item.location.lat]);
		}
		
		// 同时更新地址输入框
		hospitalForm.address = `${item.name} ${item.address}`.trim();
	}
};

// 添加带点击事件的标记
const addMarkerWithClickEvent = (position: [number, number]) => {
	// 移除现有标记
	if (marker.value) {
		map.remove(marker.value);
	}
	
	// 创建新标记
	marker.value = new (window as any).AMap.Marker({
		position: position,
	});
	
	// 为标记添加点击事件
	marker.value.on('click', () => {
		// 回显经纬度到输入框
		hospitalForm.longitude = position[0].toString();
		hospitalForm.latitude = position[1].toString();
		
		// 显示提示信息
		ElMessage.info(`已选择该位置，经度: ${position[0]}, 纬度: ${position[1]}`);
	});
	
	// 添加标记到地图
	map.add(marker.value);
};

onUpdated(async () => {
    // 设置高德地图的安全配置
    window._AMapSecurityConfig = {
        securityJsCode: "34068d35a8585449adcfdfc5b28b5006",
    };
    // 初始化地图
    if (editDialogVisible.value) { // 仅在弹窗显示时初始化地图
        map = await initMap();
        // 加载插件并绑定事件
        ({ placeSearch } = await loadPluginsAndBindEvents(map)); // 返回并解构出placeSearch
    }
});

// 初始化高德地图实例
async function initMap() {
    // 加载高德地图API，包括指定的版本和插件
    const defaultCenter = [113.85, 35.30];
    const AMap = await load({
        key: "635f2e7ebbd699fa68ef6fad1494f713", // 高德地图API Key
        version: "2.0",
        plugins: ["AMap.PlaceSearch", "AMap.AutoComplete"],
        zoom: 10,
        center: [longi.value, lati.value]
    });
    
    // 创建地图实例，设置容器ID和允许自适应窗口大小
    const mapInstance = new AMap.Map("container", {
        resizeEnable: true,
        viewMode: "2D",
        zoom: 11,
        center: longi.value && lati.value
            ? [parseFloat(longi.value), parseFloat(lati.value)]
            : defaultCenter,
    });
    
    // 如果有初始经纬度，添加标记
    if (longi.value && lati.value) {
        addMarkerWithClickEvent([parseFloat(longi.value), parseFloat(lati.value)]);
    }
    
    return mapInstance;
}

// 加载插件并绑定事件
async function loadPluginsAndBindEvents(map) {
    const autoOptions = {
        input: "tipinput", //绑定到输入框的ID
    };
    // 创建自动完成实例
    const auto = new (window as any).AMap.AutoComplete(autoOptions);
    // 创建地点搜索实例，关联到地图
    const ps = new (window as any).AMap.PlaceSearch({
        map: map,
    });
    
    // 绑定自动完成的选中事件，根据选中的地点设置城市并执行搜索
    auto.on("select", (e) => {
        ps.setCity(e.poi.adcode); //设置搜索城市为选中地点的城市编码
        ps.search(e.poi.name); //搜索选中地点的名称
        
        // 从选中的POI中获取经纬度并设置到表单
        if (e.poi.location) {
            hospitalForm.longitude = e.poi.location.lng.toString();
            hospitalForm.latitude = e.poi.location.lat.toString();
            
            // 添加带点击事件的标记
            addMarkerWithClickEvent([e.poi.location.lng, e.poi.location.lat]);
        }
    });
    
    // 地图点击事件 - 设置经纬度
    map.on('click', function (e) {
        const lng = e.lnglat.getLng();
        const lat = e.lnglat.getLat();
        
        // 设置经纬度到表单
        hospitalForm.longitude = lng.toString();
        hospitalForm.latitude = lat.toString();
        
        // 添加带点击事件的标记
        addMarkerWithClickEvent([lng, lat]);
    });
    
    return { placeSearch: ps }; // 返回placeSearch实例
}

// 点击搜索
const searchs = () => {
    // 判断用户是否输入了关键字
    if (!searchKeyword.value.trim()) {
        ElMessage.error("请输入搜索内容！");
        return;
    }
    
    // 执行地点搜索，并处理搜索结果
    placeSearch.search(searchKeyword.value, (status, result) => {
        if (status === "complete" && result.info === "OK") {
            // 如果搜索成功且有搜索结果
            if (result.poiList.pois.length > 0) {
                // 取第一个搜索结果，设置地图中心和缩放级别
                const poi = result.poiList.pois[0];
                map.setCenter([poi.location.lng, poi.location.lat]);
                map.setZoom(15); //缩放级别
                
                // 设置经纬度到表单
                hospitalForm.longitude = poi.location.lng.toString();
                hospitalForm.latitude = poi.location.lat.toString();
                
                // 更新地址输入框
                hospitalForm.address = `${poi.name} ${poi.address}`.trim();
                
                // 添加带点击事件的标记
                addMarkerWithClickEvent([poi.location.lng, poi.location.lat]);
            } else {
                ElMessage.error("未找到相关地点！");
            }
        } else {
            ElMessage.error("搜索失败！");
        }
    });
}

// 失去焦点时搜索
const searchOnBlur = () => {
    if (searchKeyword.value.trim()) {
        searchs();
    }
}

// url路径
const imageUrlPrefix = 'https://yiliao.kuxia.top/';

// 定义表格数据
const tableData = ref<any[]>([]);

// 编辑弹窗控制
const editDialogVisible = ref(false);

// 表单引用
const hospitalFormRef = ref();

// 医院表单数据
const hospitalForm = reactive({
	id: '',
	name: '',
	tel: '',
	type: '',
	address: '',
	longitude : '',
	latitude : '',
	img: '',
	profile: '',
	content: '',
	create_time: '',
});

// 表单验证规则
const hospitalRules = reactive({
	name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }],
	tel: [
		{ required: true, message: '请输入联系电话', trigger: 'blur' },
		{ pattern: /^(\d{3,4}-)?\d{7,8}$|^1[3-9]\d{9}$/, message: '请输入正确的电话号码格式', trigger: 'blur' },
	],
	type: [{ required: true, message: '请输入医院类型', trigger: 'blur' }],
	address: [{ required: true, message: '请输入医院地址', trigger: 'blur' }],
	longitude : [{ required: true, message: '请通过地图选择经度', trigger: 'blur' }],
	latitude : [{ required: true, message: '请通过地图选择纬度', trigger: 'blur' }],
	img: [{ required: true, message: '请上传医院图片', trigger: 'change' }],
	profile: [{ required: true, message: '请上传科室分布图', trigger: 'change' }],
	content: [{ required: true, message: '请输入医院详情', trigger: 'blur' }],
});

// 富文本
const editorConfig = reactive({
	autoHeightEnabled: false,
	initialFrameHeight: 200,
	initialFrameWidth: '100vw',
	UEDITOR_HOME_URL: '/UEditor/',
	serverUrl: '/pc/common/ueditor',
	uploadUrl: '/UEditor',
});

// 获取医院列表数据
const fetchHospitalList = async () => {
	try {
		const res: any = await getHospitalInfo().signIn({});
		if (res.code === 1) {
			tableData.value = res.data;
		}
	} catch (error) {
		console.error('获取医院列表失败:', error);
	}
};

// 处理编辑
const handleEdit = (row: any) => {
	// 深拷贝确保正确赋值
	Object.assign(hospitalForm, JSON.parse(JSON.stringify(row)));
	searchKeyword.value = row.address || '';
	// 设置经纬度引用，用于地图初始化
	longi.value = row.longitude || '';
	lati.value = row.latitude || '';
	
	// 确保弹窗打开后经纬度正确显示
	nextTick(() => {
		editDialogVisible.value = true;
	});
};

// 处理医院图片上传进度
const handleImgProgress = (event: any) => {
	imgUploadLoading.value = true;
	imgUploadProgress.value = Math.round((event.loaded * 100) / event.total);
};

// 处理科室分布图上传进度
const handleProfileProgress = (event: any) => {
	profileUploadLoading.value = true;
	profileUploadProgress.value = Math.round((event.loaded * 100) / event.total);
};

// 处理医院图片上传成功
const handleImgSuccess = (response: any, file: any, fileList: any) => {
	imgUploadLoading.value = false;
	imgUploadProgress.value = 0;
	
	console.log('医院图片上传响应:', response); // 调试信息
	
	if (response.code === 1) {
		hospitalForm.img = response.data.url;
		ElMessage.success('医院图片上传成功');
	} else {
		ElMessage.error(response.msg || '医院图片上传失败');
	}
};

// 处理科室分布图上传成功
const handleProfileSuccess = (response: any, file: any, fileList: any) => {
	profileUploadLoading.value = false;
	profileUploadProgress.value = 0;
	
	console.log('科室分布图上传响应:', response); // 调试信息
	
	if (response.code === 1) {
		hospitalForm.profile = response.data.url;
		ElMessage.success('科室分布图上传成功');
	} else {
		ElMessage.error(response.msg || '科室分布图上传失败');
	}
};

// 医院图片上传失败处理
const handleImgUploadError = (error: any, file: any, fileList: any) => {
	imgUploadLoading.value = false;
	imgUploadProgress.value = 0;
	
	ElMessage.error('医院图片上传失败，请重试');
	console.error('医院图片上传失败:', error);
};

// 科室分布图上传失败处理
const handleProfileUploadError = (error: any, file: any, fileList: any) => {
	profileUploadLoading.value = false;
	profileUploadProgress.value = 0;
	
	ElMessage.error('科室分布图上传失败，请重试');
	console.error('科室分布图上传失败:', error);
};

// 医院图片上传前检查
const beforeImgUpload = (file: File) => {
	const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt2M = file.size / 1024 / 1024 < 2;

	if (!isJPGOrPNG) {
		ElMessage.error('上传图片只能是 JPG/PNG 格式!');
		return false;
	}
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		return false;
	}
	
	// 重置上传状态
	imgUploadLoading.value = true;
	imgUploadProgress.value = 0;
	
	return true;
};

// 科室分布图上传前检查
const beforeProfileUpload = (file: File) => {
	const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt2M = file.size / 1024 / 1024 < 2;

	if (!isJPGOrPNG) {
		ElMessage.error('上传图片只能是 JPG/PNG 格式!');
		return false;
	}
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		return false;
	}
	
	// 重置上传状态
	profileUploadLoading.value = true;
	profileUploadProgress.value = 0;
	
	return true;
};

// 提交表单
const submitForm = () => {
	if (!hospitalFormRef.value) return;
	hospitalFormRef.value.validate(async (valid: boolean) => {
		if (valid) {
			try {
				// 构造符合接口要求的参数
				const params = {
					id: hospitalForm.id,
					name: hospitalForm.name,
					tel: hospitalForm.tel,
					type: hospitalForm.type,
					address: hospitalForm.address,
					lng: hospitalForm.longitude,
					lat: hospitalForm.latitude,
					content: hospitalForm.content,
					avatar: hospitalForm.img,
					profile: hospitalForm.profile
				};
				
				console.log('提交的参数:', params); // 调试信息
				
				const res: any = await hospitalEdit(params);
				if (res.code === 1) {
					ElMessage.success('医院信息更新成功');
					editDialogVisible.value = false;
					fetchHospitalList();
				} else {
					ElMessage.error(res.msg || '更新失败');
				}
			} catch (error) {
				ElMessage.error('更新失败');
				console.error('更新医院信息失败:', error);
			}
		}
	});
};

// 关闭弹窗时重置表单
const handleDialogClose = () => {
	if (hospitalFormRef.value) {
		hospitalFormRef.value.resetFields();
	}
	searchKeyword.value = '';
	// 清理地图实例
	if (map) {
		map.destroy();
		map = null;
	}
	marker.value = null;
	placeSearch = null;
	autoComplete.value = null;
	geocoder.value = null;
	searchSuggestions.value = [];
	
	// 重置上传状态
	imgUploadLoading.value = false;
	profileUploadLoading.value = false;
	imgUploadProgress.value = 0;
	profileUploadProgress.value = 0;
};

// 弹窗打开时的处理
const onDialogOpened = () => {
	// 确保弹窗打开后地图正确初始化
	nextTick(() => {
		if (!map && hasAmapKey.value) {
			initMap().then(amap => {
				map = amap;
				loadPluginsAndBindEvents(map).then(({ placeSearch: ps }) => {
					placeSearch = ps;
					
					// 确保经纬度正确显示
					if (hospitalForm.longitude && hospitalForm.latitude) {
						longi.value = hospitalForm.longitude;
						lati.value = hospitalForm.latitude;
					}
				});
			});
		}
	});
};

// 组件挂载时获取数据
onMounted(() => {
	fetchHospitalList();
});

// 组件卸载时清理资源
onUnmounted(() => {
	if (map) {
		map.destroy();
	}
	// 清理全局变量
	if (window.AMap) {
		delete window.AMap;
	}
});
</script>

<style scoped>
.container_box {
	width: 98%;
	height: 100%;
	background: #fff;
	margin-left: 5px;
}

.container_box > .container_title {
	border-bottom: 1px solid #eee;
	width: 100%;
	padding-left: 1%;
	height: 50px;
	line-height: 50px;
	font-size: 20px;
	font-weight: bold;
}

.avatar-uploader {
	width: 178px;
	height: 178px;
	display: block;
}

.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
	object-fit: cover;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
	display: flex;
	align-items: center;
	justify-content: center;
}

.image-loading {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(255, 255, 255, 0.9);
	display: flex;
	align-items: center;
	justify-content: center;
}

.upload-status {
	font-size: 12px;
	color: #606266;
	margin-top: 5px;
	text-align: center;
}

.el-upload__tip {
	font-size: 12px;
	color: #606266;
}

/* 地图样式 */
.map-container-wrapper {
	margin-top: 20px;
	width: 100%;
	height: 400px;
	position: relative;
	margin-bottom: 20px;
}

.map-search-container {
	margin-bottom: 10px;
}

.search-icon {
	cursor: pointer;
	color: #606266;
	transition: color 0.2s;
}

.search-icon:hover {
	color: #409eff;
}

.suggest-item {
	padding: 8px 10px;
}

.suggest-name {
	font-weight: 500;
}

.suggest-address {
	font-size: 12px;
	color: #666;
	margin-top: 4px;
}

.map-container {
	width: 100%;
	height: 340px;
	border: 1px solid #ddd;
}

.error-message {
	color: red;
	padding: 10px;
	background: #ffeeee;
	margin-bottom: 10px;
}

.loading-indicator {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.8);
	z-index: 1000;
}

/* 解决弹窗闪烁问题的关键样式 */
.address-suggestion-popup {
	z-index: 9999 !important;
}

/* 确保搜索建议面板可见 */
:deep(.el-autocomplete-suggestion) {
	z-index: 9999 !important;
	max-height: 300px;
	overflow-y: auto;
}
</style>